"""
TSDK API客户端示例
演示如何使用DJI Thermal SDK相关的API接口
"""

import requests
import json
import os
import base64
from typing import Dict, Any, List


class TSDKAPIClient:
    """TSDK API客户端"""
    
    def __init__(self, base_url: str = "http://localhost:5000"):
        """
        初始化客户端
        
        Args:
            base_url: API服务器基础URL
        """
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
        
    def check_health(self) -> Dict[str, Any]:
        """健康检查"""
        try:
            response = self.session.get(f"{self.base_url}/api/health")
            return response.json()
        except Exception as e:
            return {"error": str(e)}
    
    def get_tsdk_capabilities(self) -> Dict[str, Any]:
        """获取TSDK处理能力"""
        try:
            response = self.session.get(f"{self.base_url}/api/tsdk/capabilities")
            return response.json()
        except Exception as e:
            return {"error": str(e)}
    
    def process_rjpeg_file(self, rjpeg_path: str) -> Dict[str, Any]:
        """
        处理R-JPEG文件
        
        Args:
            rjpeg_path: R-JPEG文件路径
            
        Returns:
            处理结果
        """
        try:
            if not os.path.exists(rjpeg_path):
                return {"error": f"文件不存在: {rjpeg_path}"}
            
            with open(rjpeg_path, 'rb') as f:
                files = {'rjpeg_file': (os.path.basename(rjpeg_path), f, 'image/jpeg')}
                response = self.session.post(f"{self.base_url}/api/tsdk/process_rjpeg", files=files)
            
            return response.json()
            
        except Exception as e:
            return {"error": str(e)}
    
    def analyze_rjpeg_regions(self, rjpeg_path: str, regions: List[Dict[str, int]]) -> Dict[str, Any]:
        """
        R-JPEG区域温度分析
        
        Args:
            rjpeg_path: R-JPEG文件路径
            regions: 分析区域列表，格式: [{'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2}, ...]
            
        Returns:
            分析结果
        """
        try:
            if not os.path.exists(rjpeg_path):
                return {"error": f"文件不存在: {rjpeg_path}"}
            
            with open(rjpeg_path, 'rb') as f:
                files = {'rjpeg_file': (os.path.basename(rjpeg_path), f, 'image/jpeg')}
                data = {'regions': json.dumps(regions)}
                response = self.session.post(
                    f"{self.base_url}/api/tsdk/analyze_rjpeg_regions", 
                    files=files, 
                    data=data
                )
            
            return response.json()
            
        except Exception as e:
            return {"error": str(e)}
    
    def hybrid_process_image(self, image_path: str, mode: str = 'auto') -> Dict[str, Any]:
        """
        混合模式图像处理
        
        Args:
            image_path: 图像文件路径
            mode: 处理模式 ('auto', 'tsdk', 'hsv', 'hybrid')
            
        Returns:
            处理结果
        """
        try:
            if not os.path.exists(image_path):
                return {"error": f"文件不存在: {image_path}"}
            
            with open(image_path, 'rb') as f:
                files = {'image_file': (os.path.basename(image_path), f, 'image/jpeg')}
                data = {'mode': mode}
                response = self.session.post(
                    f"{self.base_url}/api/hybrid/process_image", 
                    files=files, 
                    data=data
                )
            
            return response.json()
            
        except Exception as e:
            return {"error": str(e)}
    
    def print_result(self, result: Dict[str, Any], title: str = "API结果"):
        """打印格式化的API结果"""
        print(f"\n{'='*60}")
        print(f"{title}")
        print('='*60)
        
        if "error" in result:
            print(f"❌ 错误: {result['error']}")
            return
        
        if not result.get('success', False):
            print(f"❌ 失败: {result.get('message', '未知错误')}")
            return
        
        print(f"✅ 成功: {result.get('message', '操作成功')}")
        
        if 'data' in result and result['data']:
            self._print_data(result['data'])
    
    def _print_data(self, data: Any, indent: int = 0):
        """递归打印数据"""
        prefix = "  " * indent
        
        if isinstance(data, dict):
            for key, value in data.items():
                if isinstance(value, (dict, list)):
                    print(f"{prefix}{key}:")
                    self._print_data(value, indent + 1)
                else:
                    print(f"{prefix}{key}: {value}")
        elif isinstance(data, list):
            for i, item in enumerate(data):
                print(f"{prefix}[{i}]:")
                self._print_data(item, indent + 1)
        else:
            print(f"{prefix}{data}")


def main():
    """主函数 - 演示API使用"""
    print("DJI Thermal SDK API客户端示例")
    print("="*50)
    
    # 初始化客户端
    client = TSDKAPIClient()
    
    # 1. 健康检查
    print("\n📡 检查API服务器状态...")
    health = client.check_health()
    client.print_result(health, "健康检查")
    
    # 2. 检查TSDK能力
    print("\n🔧 检查TSDK处理能力...")
    capabilities = client.get_tsdk_capabilities()
    client.print_result(capabilities, "TSDK能力检查")
    
    # 3. 查找测试图像文件
    test_image_dir = os.path.join(os.path.dirname(__file__), '..', 'snapshot')
    test_images = []
    
    if os.path.exists(test_image_dir):
        for filename in os.listdir(test_image_dir):
            if filename.lower().endswith(('.jpg', '.jpeg', '.png')):
                test_images.append(os.path.join(test_image_dir, filename))
    
    if not test_images:
        print("\n⚠️ 未找到测试图像文件，跳过图像处理演示")
        return
    
    test_image = test_images[0]
    print(f"\n🖼️ 使用测试图像: {os.path.basename(test_image)}")
    
    # 4. 混合模式处理 - 自动模式
    print("\n🎯 混合模式处理 (自动选择)")
    result = client.hybrid_process_image(test_image, mode='auto')
    client.print_result(result, "混合模式处理 - 自动")
    
    # 5. 混合模式处理 - HSV模式
    print("\n🌈 混合模式处理 (强制HSV)")
    result = client.hybrid_process_image(test_image, mode='hsv')
    client.print_result(result, "混合模式处理 - HSV")
    
    # 6. 混合模式处理 - TSDK模式（如果有R-JPEG文件）
    rjpeg_files = [f for f in test_images if f.lower().endswith(('.r.jpg', '.rjpeg'))]
    
    if rjpeg_files:
        rjpeg_file = rjpeg_files[0]
        print(f"\n🔬 发现R-JPEG文件: {os.path.basename(rjpeg_file)}")
        
        # 处理R-JPEG文件
        print("\n📊 R-JPEG文件处理")
        result = client.process_rjpeg_file(rjpeg_file)
        client.print_result(result, "R-JPEG文件处理")
        
        # R-JPEG区域分析
        print("\n📍 R-JPEG区域温度分析")
        test_regions = [
            {'x1': 50, 'y1': 50, 'x2': 150, 'y2': 150},    # 左上区域
            {'x1': 200, 'y1': 200, 'x2': 300, 'y2': 300}   # 右下区域
        ]
        
        result = client.analyze_rjpeg_regions(rjpeg_file, test_regions)
        client.print_result(result, "R-JPEG区域分析")
        
    else:
        print("\n📝 未发现R-JPEG文件，创建模拟R-JPEG文件演示...")
        
        # 复制一个普通图像作为模拟R-JPEG文件
        import shutil
        mock_rjpeg = os.path.join(test_image_dir, 'mock_thermal.r.jpg')
        shutil.copy2(test_image, mock_rjpeg)
        
        print(f"✅ 创建模拟R-JPEG文件: {os.path.basename(mock_rjpeg)}")
        
        try:
            # 尝试TSDK模式处理
            print("\n🔬 TSDK模式处理 (模拟)")
            result = client.hybrid_process_image(mock_rjpeg, mode='tsdk')
            client.print_result(result, "TSDK模式处理 - 模拟")
            
            # 处理R-JPEG文件
            print("\n📊 R-JPEG文件处理 (模拟)")
            result = client.process_rjpeg_file(mock_rjpeg)
            client.print_result(result, "R-JPEG文件处理 - 模拟")
            
        finally:
            # 清理模拟文件
            try:
                os.remove(mock_rjpeg)
                print(f"🗑️ 清理模拟文件: {os.path.basename(mock_rjpeg)}")
            except:
                pass
    
    # 7. 演示混合模式对比
    if capabilities.get('data', {}).get('tsdk_available', False):
        print("\n⚖️ 混合模式对比分析")
        result = client.hybrid_process_image(test_image, mode='hybrid')
        client.print_result(result, "混合模式对比")
    else:
        print("\n⚠️ TSDK不可用，跳过混合模式对比")
    
    print("\n🎉 演示完成！")
    print("\n💡 提示:")
    print("  - 如果要使用真实的TSDK功能，请确保已正确安装DJI Thermal SDK")
    print("  - 当前演示使用模拟模式，提供基本的功能测试")
    print("  - 真实的R-JPEG文件将提供更准确的温度数据")


if __name__ == '__main__':
    main()